<template>
  <!--生产计划-->
  <div id="plandata-view" ref="fullscreenElement">
    <dv-border-box1 ref="borderRef">
      <el-container v-loading="loading" :style="'height:'+screenHeight" class="full-screen-container"
                    element-loading-text="正在加载中...">
        <div class="d-flex jc-center" style="padding: 10px 30px 5px">
          <dv-decoration10 style="width:33.3%;height:5px;"/>
          <div class="d-flex jc-center">
            <dv-decoration8 :color="['#568aea', '#000000']" style="width:200px;height:50px;"/>
            <div class="title">
              <span class="title-text " @click="handleFullscreen">生产任务看板</span>
              <dv-decoration6
                  :color="['#50e3c2', '#67a1e5']"
                  :reverse="true"
                  class="title-bototm"
                  font-size=“0.2rem;”
                  style="width:250px;height:8px;"
              />
            </div>
            <dv-decoration8
                :color="['#568aea', '#000000']"
                :reverse="true"
                style="width:200px;height:50px;"
            />
          </div>
          <dv-decoration10 style="width:33.3%;height:5px;"/>
        </div>
        <div class="date">{{ nowDate + ' ' + nowTime + ' ' + nowWeek }}</div>
        <el-row :gutter="20" style="display: flex;justify-content: space-around">
          <el-col :span="4">
            <div class="el-statistic" style="background-color: #13966F"
                 @click="planDataFilterHandler('currentMothCount')">
              <div class="title">本月计划数量</div>
              <div class="value">{{ planData.currentMothCount }}</div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="el-statistic" style="background-color:#5470c6; "
                 @click="planDataFilterHandler('currentMothFinishCount')">
              <div class="title">本月完工数量</div>
              <div class="value">{{ planData.currentMothFinishCount }}</div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="el-statistic" style="background-color:#ee6666; "
                 @click="planDataFilterHandler('currentMothSuspendedCount')">
              <div class="title">停工数量</div>
              <div class="value">{{ planData.currentMothSuspendedCount }}</div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="el-statistic" style="background-color:#F2681F"
                 @click="planDataFilterHandler('afeterCurrentMothCount')">
              <div class="title">后续计划数量</div>
              <div class="value">{{ planData.afeterCurrentMothCount }}</div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="el-statistic" style="background-color:#F2681F"
                 @click="planDataFilterHandler('historyIncompleteCount')">
              <div class="title">历史未完成数量</div>
              <div class="value">{{ planData.historyIncompleteCount }}</div>
            </div>
          </el-col>
        </el-row>
        <div class="main-container">
          <div>
            <avue-crud
                ref="crud"
                :data="stateTable.data"
                :option="stateTable.option"
                :page.sync="stateTable.pages"
                :search.sync="searchParams"
                @size-change="handleChangeSize"
                @current-change="handleChangeCurrent"
                @refresh-change="handleRefresh"
                @search-change="handleSearch"
                @search-reset="handleReset"
                @sort-change="handleSort"
            >
              <template #showLevel="{row}">
                <el-tooltip v-if="row.showLevel == 1" class="item" content="已经超期了" effect="dark" placement="top-start">
                  <el-icon :size="20" color="red">
                    <BellFilled/>
                  </el-icon>
                </el-tooltip>
                <el-tooltip v-else-if="row.showLevel == 2" class="item" content="剩余交付时间5天内" effect="dark"
                            placement="top-start">
                  <el-icon :size="20" color="orange">
                    <BellFilled/>
                  </el-icon>
                </el-tooltip>
                <el-tooltip v-else-if="row.showLevel == 3" class="item" content="剩余交付时间5到10天内" effect="dark"
                            placement="top-start">
                  <el-icon :size="20" color="yellow">
                    <BellFilled/>
                  </el-icon>
                </el-tooltip>
                <el-tooltip v-else-if="row.showLevel == 4" class="item" content="交付日期可控" effect="dark"
                            placement="top-start">
                  <el-icon :size="20" color="green">
                    <BellFilled/>
                  </el-icon>
                </el-tooltip>
                <el-tooltip v-else-if="row.showLevel == 5" class="item" content="还未派工" effect="dark"
                            placement="top-start">
                  <el-icon :size="20" color="gray">
                    <BellFilled/>
                  </el-icon>
                </el-tooltip>
                <el-tooltip v-else-if="row.showLevel == 6" class="item" content="已经入库" effect="dark"
                            placement="top-start">
                  <el-icon :size="20" color="lightgreen">
                    <BellFilled/>
                  </el-icon>
                </el-tooltip>
              </template>
              <template #finishRate="{row}">
                <el-progress v-if="isNaN(parseInt(row.finishRate))" :percentage="0" :stroke-width="20"
                             text-inside></el-progress>
                <el-progress v-else-if="parseInt(row.finishRate)>=0" :percentage="row.finishRate" :stroke-width="20"
                             status="exception" text-inside></el-progress>
                <el-progress v-else-if="parseInt(row.finishRate)>20" :percentage="row.finishRate" :stroke-width="20"
                             status="warning" text-inside></el-progress>
                <el-progress v-else-if="parseInt(row.finishRate)>50" :percentage="row.finishRate" :stroke-width="20"
                             text-inside></el-progress>
                <el-progress v-else-if="parseInt(row.finishRate)>80" :percentage="row.finishRate" :stroke-width="20"
                             status="success" text-inside></el-progress>
              </template>
              <template #problemClassifyList="{ row }">
                <div v-if="row.problemClassifyList && row.problemClassifyList.length>0">
                  <el-button v-for="item in row.problemClassifyList" :key="item.id" type="text"
                             @click="openProblem(item,row)">
                    {{ item + ' ' }}
                  </el-button>
                </div>
              </template>
              <template #debug="{ row }">
                <el-button v-if="row.debug" style="width: 100%" type="text" @click="openPlan('debug', row)">
                  <i class="el-icon-check" style="color:#31B48D;width:100%;font-size: 2.8em;font-weight: 600"></i>
                </el-button>
              </template>
              <template #factoryCheck="{ row }">
                <el-button v-if="row.factoryCheck" style="width: 100%" type="text"
                           @click="openPlan('factoryCheck', row)">
                  <i class="el-icon-check" style="color:#31B48D;width:100%;font-size: 2.8em;font-weight: 600"></i>
                </el-button>
              </template>
              <template #armyCheck="{ row }">
                <el-button v-if="row.armyCheck" style="width: 100%" type="text" @click="openPlan('armyCheck', row)">
                  <i class="el-icon-check" style="color:#31B48D;width:100%;font-size: 2.8em;font-weight: 600"></i>
                </el-button>
              </template>
              <template #transfer="{ row }">
                <el-button v-if="row.transfer" style="width: 100%" type="text" @click="openPlan('transfer', row)">
                  <i class="el-icon-check" style="color:#31B48D;width:100%;font-size: 2.8em;font-weight: 600"></i>
                </el-button>
              </template>
            </avue-crud>
            <div
                style="position: relative;width:100%;top: -1px;height: 1px;background-color: #0f1325;z-index: 100000;"></div>
          </div>
        </div>
      </el-container>
    </dv-border-box1>
    <!--    <mouth-plan-index ref="mouthPlanRef"></mouth-plan-index>-->
    <!--    <problem ref="planProblemRef"></problem>-->
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted, onBeforeUnmount} from 'vue';
import {getList, getCount} from "../../../apis/mes/workProgress";
import {formatDate} from "../../../utils/formatTime";
// import MouthPlanIndex from "@/views/board/plan/mouthPlan.vue";
// import problem from "@/views/board/plan/problem.vue";

// 响应式数据
const loading = ref(true);
const screenHeight = ref(window.screen.height + 'px' || '1088px');
const nowDate = ref("");
const nowTime = ref("");
const nowWeek = ref("");
const interval = ref(null);
const fullscreenElement = ref(null);
const mouthPlanRef = ref(null);
const planProblemRef = ref(null);
const crudRef = ref(null);
const fullScreen = ref(false);

// 统计卡片配置
const statTitles = {
  currentMothCount: '本月计划数量',
  currentMothFinishCount: '本月完工数量',
  currentMothSuspendedCount: '停工数量',
  afeterCurrentMothCount: '后续计划数量',
  historyIncompleteCount: '历史未完成数量'
};

const statCardStyles = {
  currentMothCount: 'background-color: #13966F',
  currentMothFinishCount: 'background-color:#5470c6;',
  currentMothSuspendedCount: 'background-color:#ee6666;',
  afeterCurrentMothCount: 'background-color:#F2681F',
  historyIncompleteCount: 'background-color:#F2681F'
};

// 计划数据
const planData = reactive({
  currentMothCount: 0,
  currentMothFinishCount: 0,
  currentMothSuspendedCount: 0,
  afeterCurrentMothCount: 0,
  historyIncompleteCount: 0,
});

// 表格相关状态
const searchParams = reactive({
  orderBy: "createTime",
  orderMethod: "desc",
});

const stateTable = reactive({
  data: [],
  loading: false,
  selectionRow: [],
  pages: {
    total: 0,
    currentPage: 1,
    pageSize: 20,
    pageSizes: [10, 20, 50, 100, 200, 300, 500],
  },
  option: {
    index: true,
    indexWidth: 40,
    header: false,
    border: false,
    addBtn: false,
    menu: false,
    editBtn: false,
    delBtn: false,
    viewBtn: false,
    excelBtn: false,
    stripe: true,
    height: computed(() => `calc(${screenHeight.value} - 180px)`),
    searchShow: false,
    column: [
      {
        label: "警示灯",
        prop: "showLevel",
        align: "center",
        formatter: (val) => {
          return val.ling;
        },
        width: 55,
      }, {
        label: "计划编号",
        prop: "planCode",
        align: "center",
      }, {
        label: "批次",
        prop: "batchNum",
        align: "center",
        width: 100,
        overHidden: true
      }, {
        label: "项目号",
        prop: "workOrderCode",
        align: "center",
      }, {
        label: "项目名称",
        prop: "planAuditOrderName",
        align: "center",
      }, {
        label: "产品型号",
        prop: "modelName",
        align: "center",
        width: 100,
      }, {
        label: "产品名称",
        prop: "productName",
        align: "center",
        width: 100,
        overHidden: true
      }, {
        label: "产品编号",
        prop: "productCode",
        align: "center",
        width: 120,
        overHidden: true
      }, {
        label: "产品主管",
        prop: "assignerName",
        align: "center",
        width: 80,
      }, {
        label: "数量",
        prop: "quantity",
        align: "center",
        width: 70,
      }, {
        label: "生产调试",
        prop: "debug",
        align: "center",
        width: 120,
      }, {
        label: "所检",
        prop: "factoryCheck",
        align: "center",
        width: 70,
      },
      {
        label: "军检",
        prop: "armyCheck",
        align: "center",
        width: 70,
      },
      {
        label: "入库",
        prop: "transfer",
        align: "center",
        width: 70,
      },
      {
        label: '完工率',
        prop: 'finishRate',
        formatter: (val) => {
          if (!isNaN(parseInt(val.finishRate))) {
            return parseInt(val.finishRate);
          } else {
            return 0;
          }
        },
        width: 70,
      },
      {
        label: "停工原因",
        prop: "problemClassifyList",
        overHidden: true,
        headerAlign: 'center',
        align: 'center',
        width: 180
      },
      {
        label: "计划结束日期",
        prop: "needEndDate",
        sort: true,
        editDisplay: false,
        formatter: (row) => {
          return formatDate(row.needEndDate, "yyyy-MM-dd");
        },
        width: 100,
      }
    ],
  }
});
// 计算属性
const defaultSearch = computed(() => ({
  orderBy: "code",
  orderMethod: "asc",
}));
const crudHeight = computed(() =>  `calc(${screenHeight.value} - 180px)`);

// 方法定义
const getDate = () => {
  const now = new Date();
  const yy = now.getFullYear();
  const mm = now.getMonth() + 1;
  const dd = now.getDate();
  const week = now.getDay();
  const hh = now.getHours();
  const mf = now.getMinutes().toString().padStart(2, "0");

  const weekMap = {
    0: "星期日",
    1: "星期一",
    2: "星期二",
    3: "星期三",
    4: "星期四",
    5: "星期五",
    6: "星期六",
  };

  nowWeek.value = weekMap[week];
  nowTime.value = `${hh}:${mf}`;
  nowDate.value = `${yy}/${mm}/${dd}`;
};
const currentTime = () => {
  interval.value = setInterval(getDate, 1000);
};

const handleKeyPress = (event) => {
  if (event.key === "F11") {
    event.preventDefault();
    fullScreen.value ? exitFullscreen() : enterFullscreen();
  }
};

const handleFullscreen = () => {
  fullScreen.value ? exitFullscreen() : enterFullscreen();
};
const enterFullscreen = () => {
  const element = fullscreenElement.value;
  if (!element) return;

  const methods = [
    'requestFullscreen',
    'mozRequestFullScreen',
    'webkitRequestFullscreen',
    'msRequestFullscreen'
  ];

  const method = methods.find(m => element[m]);
  if (method) element[method]();
  fullScreen.value = true;
};

const exitFullscreen = () => {
  const methods = [
    'exitFullscreen',
    'mozCancelFullScreen',
    'webkitExitFullscreen',
    'msExitFullscreen'
  ];

  const method = methods.find(m => document[m]);
  if (method) document[method]();
  fullScreen.value = false;
};

const getPlan = () => {
  getCount().then((res) => {
    if (res.success && res.obj) {
      Object.assign(planData, {
        currentMothCount: res.obj.currentMothCount,
        currentMothFinishCount: res.obj.currentMothFinishCount,
        currentMothSuspendedCount: res.obj.currentMothSuspendedCount,
        afeterCurrentMothCount: res.obj.afeterCurrentMothCount,
        historyIncompleteCount: res.obj.historyCount,
      });
    }
  });
};

const planDataFilterHandler = (val) => {
  loading.value = true;

  const valueMap = {
    currentMothCount: 'thisMonth',
    currentMothFinishCount: 'thisMonthFinish',
    currentMothSuspendedCount: 'SuspendedList',
    afeterCurrentMothCount: 'followUpList',
    historyIncompleteCount: 'historyList'
  };

  const params = {...searchParams, dataSegType: valueMap[val]};
  getList(params).then(data => {
    loading.value = false;
    stateTable.data = data || [];
  });
};

const getTableList = () => {
  stateTable.loading = true;
  const {pageSize, currentPage} = stateTable.pages;
  const params = {
    pageSize: pageSize,
    pageNum: currentPage,
    ...searchParams
  }
  getList(params).then((data) => {
    stateTable.loading = false;
    stateTable.data = data || [];
  });
};

const handleReset = () => {
  Object.assign(searchParams, defaultSearch.value);
  getTableList();
};

const handleRefresh = () => {
  getTableList();
};

const handleSearch = (params, done) => {
  setTimeout(() => {
    done();
    Object.assign(searchParams, params);
    getTableList();
  }, 300);
};

const handleSort = (val) => {
  searchParams.orderMethod = val.order === "descending" ? "desc" : "asc";
  searchParams.orderBy = val.prop;
  getTableList();
};

const openPlan = (type, row) => {
  mouthPlanRef.value?.openDialog(type, row);
};

const openProblem = (type, row) => {
  planProblemRef.value?.openDialog(type, row);
};
const handleChangeSize = (val) => {
  stateTable.pages.pageSize = val;
  stateTable.pages.currentPage = 1;
}

// 处理当前页码变化
const handleChangeCurrent = (val) => {
  stateTable.pages.currentPage = val
}

// 生命周期钩子
onMounted(() => {
  setTimeout(() => {
    loading.value = false;
  }, 2000);

  currentTime();
  document.addEventListener("keydown", handleKeyPress);
  getPlan();
  getTableList();
});

onBeforeUnmount(() => {
  if (interval.value) clearInterval(interval.value);
  document.removeEventListener("keydown", handleKeyPress);
});
</script>

<style lang="scss" scoped>
.d-flex {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

.jc-center {
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
}

.jc-between {
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

#plandata-view {
  width: 100%;
  height: 100vh;
  min-height: 600px;
  background-size: 100% 100%;
  color: #fff;

  .full-screen-container {
    background-image: url("./img/bg.png") !important;
    width: 100%;
    height: 100%;
    transform: scale(1);
    box-shadow: 0 0 3px blue;
    display: flex;
    flex-direction: column;
  }

  .title {
    position: relative;
    width: 500px;
    text-align: center;
    background-size: cover;
    background-repeat: no-repeat;

    .title-text {
      font-size: 2.0rem;
      position: absolute;
      bottom: 5px;
      left: 50%;
      transform: translate(-50%);
    }

    .title-bototm {
      position: absolute;
      bottom: -20px;
      left: 50%;
      transform: translate(-50%);
    }
  }

  .date {
    text-align: right;
    padding: 0 50px;
    position: relative;
    top: -20px;
    font-size: 16px;
  }

  .el-statistic {
    width: 200px;
    margin: 0 auto 20px;
    color: #fff;
    background-color: #91cc75;
    padding: 10px;
    border-radius: 5px;

    .title {
      width: 100%;
      font-weight: 600;
      font-size: 1.4rem;
      line-height: 1.8rem;
    }

    .value {
      font-weight: 600;
      font-size: 18px;
      text-align: center;
    }
  }

  .main-container {
    padding: 0;
  }

  ::v-deep {
    .avue-crud .el-table {
      background-color: #0A1D32;
    }

    .avue-crud .el-table .el-table__row {
      background-color: #0A1D32;
    }
  }
}
</style>

<style lang="scss">
#plandata-view {
  .el-card {
    background-color: transparent;
  }

  .el-table {
    --el-table-border-color: transparent;
  }

  .el-table th.el-table__cell {
    background-color: #06133e !important;
    color: #56CCDB !important;
    border-color: transparent !important;
    font-size: 19px;
  }
  .el-table__body tr.current-row>td.el-table__cell{
    background-color: rgb(105 112 119) !important;
  }
  .el-table tbody {
    font-size: 18px;
  }

  .el-table tr {
    background-color: #171c3380;
    color: #56CCDB !important;
  }

  .el-table__body tr.hover-row.current-row > td.el-table__cell, .el-table__body tr.hover-row.el-table__row--striped.current-row > td.el-table__cell, .el-table__body tr.hover-row.el-table__row--striped.selection-row > td.el-table__cell, .el-table__body tr.hover-row.el-table__row--striped > td.el-table__cell, .el-table__body tr.hover-row.selection-row > td.el-table__cell, .el-table__body tr.hover-row > td.el-table__cell {
    background-color: #0f132580;
    color: #56CCDB !important;
  }

  .el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell, .el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
    background-color: #0f132580;
  }

  .el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf, .el-table--border, .el-table--group {
    border-color: transparent !important;
  }

  .el-table, .el-table__expanded-cell {
    background-color: rgba(53, 53, 54, 0.5);
  }

  .el-progress-bar__outer {
    background-color: #808080;
  }
}
</style>
